package com.aabte.weather.weatherredis.weather;

import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class QuartzConfiguration {

    private static final int MIN_INTERVAL_SECONDS = 120;
    private static final int CACHE_TIME_OFFSET = 120;

    @Resource
    private WeatherProperties weatherProperties;

    @Bean
    public JobDetail weatherDataSyncJobJobDetail() {
        return JobBuilder.newJob(WeatherDataSyncJob.class)
                .withIdentity(WeatherDataSyncJob.class.getName())
                .storeDurably()
                .build();
    }

    @Bean
    public Trigger sampleJobTrigger() {
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInSeconds(getIntervalSeconds())
                .repeatForever();
        return TriggerBuilder.newTrigger()
                .forJob(weatherDataSyncJobJobDetail())
                .withIdentity(WeatherDataSyncJob.class.getName() + "|Trigger")
                .withSchedule(scheduleBuilder)
                .build();
    }

    private int getIntervalSeconds() {
        return Math.max(MIN_INTERVAL_SECONDS, weatherProperties.getCacheTimeoutSeconds() - CACHE_TIME_OFFSET);
    }

}
